<?php

define('ROOTPATH', dirname(dirname(__FILE__) ));

$paths[] = ROOTPATH . DIRECTORY_SEPARATOR . 'Source' . DIRECTORY_SEPARATOR . 'Core';
$paths[] = ROOTPATH . DIRECTORY_SEPARATOR . 'Source' . DIRECTORY_SEPARATOR . 'Model';
$appPath = implode(PATH_SEPARATOR, $paths);
set_include_path($appPath . PATH_SEPARATOR . get_include_path());

function __autoload($class)
{
	$classFile = str_replace(' ', DIRECTORY_SEPARATOR, ucwords(str_replace('_', ' ', $class)));
	$classFile.= '.php';
	return include $classFile;
}



class Merce{
	
	private static $_appcontextpath = ROOTPATH ; 
	
	private static  $_registry = array();
	
	public static function getAppcontextpath(){
		return self::$_appcontextpath;
	}
	
	public static function register($k , $val = null){
		if(!isset(Merce::$_registry[$k])){
			if(!isset($val)){
				$val = new $k();
			}
			self::$_registry[$k] = $val;
		}
	}
	
	public static  function unregister($k){
		if(isset(Merce::$_registry[$k])){
			if (is_object(self::$_registry[$k]) && (method_exists(self::$_registry[$k], '__destruct'))) {
				self::$_registry[$k]->__destruct();
			}
			unset(Merce::$_registry[$k]);
		}
	}
	
	public static function getSingleton($k){
		if(!isset(Merce::$_registry[$k])){
			self::register($k, self::getResource($k));
		}
		return Merce::$_registry[$k];
	}
	
	public static function getResource($class , $arg = array()){
		return new $class($arg);
	}
	
	public static function getUrl($k , $url){
		if(!isset(Merce::$_registry[$k])){
			self::register($k, new Base_Model_Config());
		}
		return Merce::$_registry[$k]->get($url);
	}
	
	public static function render($action){
		
		$params = isset($_REQUEST['action'])?"/".$_REQUEST['action']:"/";
		if(isset($this->_control->attributes()->class)){
			$class = (string)$this->_control->attributes()->class;
			$control = new $class();
			$method = isset($_REQUEST['method'])?$_REQUEST['method']:isset($this->_control->attributes()->method)?(string)$this->_control->attributes()->method:'init';
			$var = $control->$method();
			if(isset($var)){
				if(is_array($var)){
					foreach (array_keys($var) as $k){
						$avar = (string)$k;
						$$avar = $var[$k];
					}
				}else {
					echo $respone;
				}
			}
				
		}
		foreach ($this->_control->children() as $child ){
			$available = (string)$child->attributes()->name;
			$$available =  (string)$child->attributes()->value;
		}
		if(isset($this->_control->attributes()->template)){
			include ( (string)$this->_control->attributes()->template ) ;
		}
	
	}
}